//
//  Scan_Vc.swift
//  MikerShoppingApp
//
//  Created by eme on 2016/10/31.
//  Copyright © 2016年 eme. All rights reserved.
//

/*
 owner:cy
 update:2016年10月31日16:15:403
 info: 扫一扫
 model: UserModel
 viewmodel: LoginViewModel
 */
import RxSwift
import UIKit
import AVFoundation




class Scan_Vc: BaseUmeng_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var scan_Content_V: UIView!
    
    @IBOutlet weak var footer_V: UIView!
    
    @IBOutlet weak var bottom_Lb: UILabel!
    
    
    @IBOutlet weak var zp_Btn: UIButton!
    
    @IBOutlet weak var sys_Btn: UIButton!
    
    @IBOutlet weak var yy_Btn: UIButton!
    
    @IBOutlet weak var sh_Btn: UIButton!
    
    @IBOutlet weak var scan_Line_ImgV: UIImageView!
    
    @IBOutlet weak var scan_Line_HeightLc: NSLayoutConstraint!
    
    @IBOutlet weak var content_V: UIView!
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    ///扫描动画
    var isAnimationing:Bool = true
    var startY:CGFloat = 5.0
    var isDown:Bool = true
    /// 定时器
    var timer:NSTimer!
    
    // MARK: - 懒加载
    // 会话
    private lazy var session : AVCaptureSession = AVCaptureSession()
    
    // 拿到输入设备
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        // 获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do{
            // 创建输入对象
            let input = try AVCaptureDeviceInput(device: device)
            return input
        }catch
        {
            print(error)
            return nil
        }
    }()
    
    // 拿到输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    // 创建预览图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 2.开始扫描
        startScan()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.stepAnimation()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // sender 一般是 button，但可以是任何东西
        if let identifier = segue.identifier { // 检查是否 nil
            switch identifier {
            default: break
            }
        }
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "scan-open"), style: .Plain, target: self, action: #selector(changeTorch))
        
//        self.zp_Btn.changeEdgeVertical(5.0)
//        self.sys_Btn.changeEdgeVertical(5.0)
//        self.yy_Btn.changeEdgeVertical(5.0)
//        self.sh_Btn.changeEdgeVertical(5.0)
        
//        self.sys_Btn.selected = true
        
        // 启用计时器，控制每秒执行一次tickDown方法
        timer = NSTimer.scheduledTimerWithTimeInterval(0.02,
                                                       target:self,selector:#selector(Scan_Vc.stepAnimation),
                                                       userInfo:nil,repeats:true)
    
    }

  
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
//        self.zp_Btn.rx_tap.subscribeNext{[unowned self] _ in
//            self.scanType = .zp
//            self.openPhotoAlbum()
//        }.addDisposableTo(disposeBag)
//        
//        self.sys_Btn.rx_tap.subscribeNext{_ in
//            self.sys_Btn.selected = true
//            self.yy_Btn.selected = false
//            self.sh_Btn.selected = false
//            self.scanType = .sys
//            }.addDisposableTo(disposeBag)
//        
//        self.yy_Btn.rx_tap.subscribeNext{_ in
//            self.sys_Btn.selected = false
//            self.yy_Btn.selected = true
//            self.sh_Btn.selected = false
//            self.scanType = .yy
//            }.addDisposableTo(disposeBag)
//        
//        self.sh_Btn.rx_tap.subscribeNext{_ in
//            self.sys_Btn.selected = false
//            self.yy_Btn.selected = false
//            self.sh_Btn.selected = true
//            self.scanType = .sh
//            }.addDisposableTo(disposeBag)
    
    }
    
    
}
extension Scan_Vc: UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    
    //MARK: -----相册选择图片识别二维码 （条形码没有找到系统方法）
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        var image:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage
        
        if (image == nil )
        {
            image = info[UIImagePickerControllerOriginalImage] as? UIImage
        }
        
        if(image != nil)
        {
            let arrayResult = self.recognizeQRImage(image!)
            self.showAlert("", title: arrayResult, handler: nil)
           return
        }
        self.showAlert("", title: "识别失败", handler: nil)
    }
    

    func openPhotoAlbum()
    {
        if EmePermission.accessPhoto() != true {
            return self.view.makeEmeToast(alertmsg[101012000]!.msgtitle)
        }
        let picker = UIImagePickerController()
        
        picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        
        picker.delegate = self;
        
        picker.allowsEditing = true
        
        self.presentViewController(picker, animated: true, completion: nil)
        
        
        
        
    }
}


extension Scan_Vc{

    /**
     识别二维码码图像
     
     - parameter image: 二维码图像
     
     - returns: 返回识别结果
     */
    func recognizeQRImage(image:UIImage) ->String
    {
        var returnResult:String = ""
        let detector:CIDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])!
        
        let img = CIImage(CGImage: (image.CGImage)!)
        
        let features:[CIFeature]? = detector.featuresInImage(img, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
        
        if( features != nil && features?.count > 0)
        {
            let feature = features![0]
            
            if feature.isKindOfClass(CIQRCodeFeature)
            {
                let featureTmp:CIQRCodeFeature = feature as! CIQRCodeFeature
                
                let scanResult = featureTmp.messageString
                
                if let scanResult = scanResult {
                    returnResult = scanResult
                }
            }
        }
        
        return returnResult
    }


}
extension Scan_Vc{
 
    // MARK: - 扫描二维码
    private func startScan(){
        
        // 1.判断是否能够将输入添加到会话中
        if !session.canAddInput(deviceInput)
        {
            return
        }
        // 2.判断是否能够将输出添加到会话中
        if !session.canAddOutput(output)
        {
            return
        }
        // 3.将输入和输出都添加到会话中
        session.addInput(deviceInput)
        session.addOutput(output)
        //        output.rectOfInterest = cropRect
        // 4.设置输出能够解析的数据类型
        // 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
        output.metadataObjectTypes =  output.availableMetadataObjectTypes
        // 5.设置输出对象的代理, 只要解析成功就会通知代理
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        // 添加预览图层,必须要插入到最下层的图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        
        // 6.告诉session开始扫描
        session.startRunning()
    }
    func stepAnimation()
    {
        if (!isAnimationing) {
            return;
        }
        
        let maxHeight:CGFloat =  self.content_V.frame.size.height
        UIView.animateWithDuration(1.4, animations: { () -> Void in
            if self.isDown == true{
                self.startY += 2
                if self.startY >= maxHeight - 5{
                    self.isDown = false
                }else{
                    self.isDown = true
                }
                
            }else{
                self.startY -= 2
                if self.startY <= 5{
                    self.isDown = true
                }else{
                    self.isDown = false
                }
            }
            self.scan_Line_HeightLc.constant = self.startY
            
            }, completion:{ (value: Bool) -> Void in
                
                
        })
        
    }
    
    func stopStepAnimating()
    {
        isAnimationing = false;
    }
    
    func isGetFlash()->Bool
    {
        if (deviceInput != nil)
        {
            return true
        }
        return false
    }
    
    
    /**
     ------闪光灯打开或关闭
     */
    func changeTorch()
    {
        if isGetFlash()
        {
            do
            {
                try deviceInput?.device.lockForConfiguration()
                
                var torch = false
                
                if deviceInput?.device.torchMode == AVCaptureTorchMode.On
                {
                    torch = false
                }
                else if deviceInput?.device.torchMode == AVCaptureTorchMode.Off
                {
                    torch = true
                }
                
                deviceInput?.device.torchMode = torch ? AVCaptureTorchMode.On : AVCaptureTorchMode.Off
                
                deviceInput?.device.unlockForConfiguration()
            }
            catch let error as NSError {
                print("device.lockForConfiguration(): \(error)")
                
            }
        }
    }
    
}
// MARK: - AVCaptureMetadataOutputObjectsDelegate
extension Scan_Vc: AVCaptureMetadataOutputObjectsDelegate
{
    // 只要解析到数据就会调用
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
    {
        // 注意: 要使用stringValue
        print(metadataObjects.last?.stringValue)
        self.showAlert("", title: metadataObjects.last?.stringValue ?? "", handler: nil)
    }
}
